<script setup lang="ts">
import { computed, h, reactive, ref, shallowRef, watch } from 'vue';
import type { TreeOption } from 'naive-ui';
import { NTree } from 'naive-ui';
// 添加类型声明（需在文件顶部添加类型导入）
import type { TransferRenderSourceList } from 'naive-ui/es/transfer/src/interface';
import { $t } from '@/locales';
import {
  fetchGetAllPages,
  fetchGetDepartmentTree,
  fetchGetMenuIdsByRoleId,
  fetchGetMenuTree,
  fetchUpdateRolePermissions
} from '@/service/api';

defineOptions({
  name: 'MenuAuthModal'
});

interface Props {
  /** the roleId */
  roleId: number;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

function flattenTree(list: undefined | Api.SystemManage.MenuTree[]): Api.SystemManage.MenuTree[] {
  const result: Api.SystemManage.MenuTree[] = [];
  function flatten(_list: Api.SystemManage.MenuTree[] = []) {
    _list.forEach(item => {
      result.push(item);
      flatten(item.children);
    });
  }
  flatten(list);
  return result;
}
function closeModal() {
  visible.value = false;
}

const title = computed(() => $t('common.edit') + $t('page.manage.role.menuAuth'));

const home = shallowRef('');

async function getHome() {
  home.value = 'home';
}

const pages = shallowRef<string[]>([]);

async function getPages() {
  const { error, data } = await fetchGetAllPages();

  if (!error) {
    pages.value = data;
  }
}

const pageSelectOptions = computed(() => {
  const opts: CommonType.Option[] = pages.value.map(page => ({
    label: page,
    value: page
  }));

  return opts;
});

const tree = shallowRef<Api.SystemManage.MenuTree[]>([]);
const treeOptions = shallowRef<Api.SystemManage.MenuTree[]>([]);

async function getTree() {
  const { error, data } = await fetchGetMenuTree();

  if (!error) {
    tree.value = data;
    treeOptions.value = flattenTree(data);
  }
}
type Model = Api.SystemManage.RolePerUpdate;
const model: Model = reactive({
  id: props.roleId,
  homeKey: 'home',
  menuIds: [],
  dataScope: 0,
  deptIds: []
});

// 修改部门树options类型声明
const departmentOptions = ref<TreeOption[]>([]); // 改为TreeOption数组类型

// 修改部门数据处理函数
async function getDepartmentOptions() {
  const { error, data } = await fetchGetDepartmentTree();
  if (!error) {
    const formatChildren = (nodes?: Api.SystemManage.Dept[] | null): TreeOption[] | undefined => {
      if (!nodes) return undefined;
      return nodes.map(node => ({
        ...node,
        key: node.id, // 添加TreeOption必须的key字段
        label: node.deptName, // 添加TreeOption必须的label字段
        children: formatChildren(node.children)
      })) as TreeOption[]; // 类型断言
    };

    departmentOptions.value = formatChildren(data) || [];
  }
}
async function updateHome(val: string) {
  // request

  model.homeKey = val;
}
const isShow = ref(false);
async function updateDataScope(val: string) {
  model.dataScope = val;
  if (val === '3') {
    isShow.value = true;
  } else {
    isShow.value = false;
  }
}
// const checks = shallowRef<number[]>([]);
// const btnChecks = shallowRef<number[]>([]);

async function getChecks() {
  // request
  const { data } = await fetchGetMenuIdsByRoleId(props.roleId);
  if (data) {
    model.menuIds = data.menuIds;
    model.homeKey = data.homeKey;
    model.dataScope = data.dataScope;
    model.deptIds = data.deptIds;
  }
}

async function handleSubmit() {
  console.log(model, props.roleId);
  model.id = props.roleId;
  const { error } = await fetchUpdateRolePermissions(model);
  if (error) {
    return;
  }
  // request
  window.$message?.success?.($t('common.modifySuccess'));

  closeModal();
}

function init() {
  // 开启模态框
  visible.value = true;
  getHome();
  getPages();
  getTree();
  getChecks();
  getDepartmentOptions();
  // 关闭模态框
}

watch(visible, val => {
  if (val) {
    if (props.roleId !== -1) {
      init();
    }
  }
});

const options = ref([
  {
    label: '仅本人数据权限',
    value: 0
  },
  {
    label: '本部门数据权限',
    value: 1
  },
  {
    label: '本部门及以下数据权限',
    value: 2
  },
  {
    label: '自定义数据权限',
    value: 3
  },
  {
    label: '全部数据权限',
    value: 4
  }
]);

// 优化后的代码（L170-L185）
const renderSourceList: TransferRenderSourceList = ({ onCheck, pattern }) =>
  h(NTree, {
    style: 'margin: 0 4px;',
    keyField: 'value',
    checkable: true,
    selectable: false,
    blockLine: true,
    checkOnClick: true,
    data: tree.value as unknown as TreeOption[],
    pattern,
    checkedKeys: model.menuIds,
    onUpdateCheckedKeys: (checkedKeys: Array<number>) => {
      model.menuIds = checkedKeys;
      onCheck(checkedKeys);
    }
  });
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-480px">
    <div class="flex-y-center gap-16px pb-12px">
      <div>{{ $t('page.manage.menu.home') }}</div>
      <NSelect
        :value="model.homeKey"
        :options="pageSelectOptions"
        size="small"
        class="w-160px"
        @update:value="updateHome"
      />
    </div>
    <div class="flex-y-center gap-16px pb-12px">
      <div>权限范围</div>
      <NSelect
        v-model:value="model.dataScope"
        :options="options"
        size="small"
        class="w-200px"
        @update:value="updateDataScope"
      />
    </div>
    <div class="mt-16px flex-y-center gap-16px">
      <div>菜单按钮权限</div>
    </div>
    <div class="mt-16px flex-y-center gap-16px">
      <NTransfer
        v-model:value="model.menuIds"
        :options="treeOptions"
        :render-source-list="renderSourceList"
        source-filterable
      />
    </div>
    <NCard v-if="model.dataScope === 3" title="自定义数据权限" size="small" class="mt-16px">
      <div class="mt-16px flex-y-center gap-16px">
        <NTree
          v-model:checked-keys="model.deptIds"
          :data="departmentOptions"
          block-line
          checkable
          expand-on-click
          virtual-scroll
          class="h-280px"
        />
      </div>
    </NCard>

    <template #footer>
      <NSpace justify="end">
        <NButton size="small" class="mt-16px" @click="closeModal">
          {{ $t('common.cancel') }}
        </NButton>
        <NButton type="primary" size="small" class="mt-16px" @click="handleSubmit">
          {{ $t('common.confirm') }}
        </NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
